package com.optimus.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.optimus.model.mapped.CustomerBean;

public class CustomerDAOImpl extends SimpleJdbcDaoSupport implements CustomerDAO
{

	@Override
	public void insertIntoDB(CustomerBean entity)
	{
		String sqlCommand = "insert into customer (customer_id, fullname, username, password, email, is_admim) values (?, ?, ?, ?, ?, ?)";
		getJdbcTemplate().update(sqlCommand, new Object[] { null, entity.getFullname(),
				entity.getUsername(), entity.getPassword(), entity.getEmail(), entity.isAdmin() });
	}

	@Override
	public CustomerBean selectEntityFromDbById(int id)
	{
		String query = "SELECT * FROM customer WHERE customer_id=?";

		try
		{
			return (CustomerBean) getJdbcTemplate().queryForObject(query, new Object[] { Integer
					.valueOf(id) }, new RowMapper<CustomerBean>()
			{
				public CustomerBean mapRow(ResultSet resultSet, int rowNum) throws SQLException
				{
					return new CustomerBean(resultSet.getInt("customer_id"), resultSet
							.getString("fullname"), resultSet.getString("username"), resultSet
							.getString("password"), resultSet.getString("email"), resultSet
							.getBoolean("is_admim"));
				}
			});
		}
		catch (IncorrectResultSizeDataAccessException e)
		{
			Logger logger = Logger.getLogger(CustomerDAOImpl.class);
			logger.error(e.getMessage());
			return null;
		}
		catch (DataAccessException e)
		{
			Logger logger = Logger.getLogger(CustomerDAOImpl.class);
			logger.error(e.getMessage());
			return null;
		}
	}

	@Override
	public CustomerBean selectCustomerByUsername(String username)
	{
		String query = "SELECT * FROM customer WHERE username=?";

		try
		{
			return (CustomerBean) getJdbcTemplate().queryForObject(query, new Object[] { username },
					new RowMapper<CustomerBean>()
					{
						public CustomerBean mapRow(ResultSet resultSet, int rowNum)
								throws SQLException
						{
							return new CustomerBean(resultSet.getInt("customer_id"), resultSet
									.getString("fullname"), resultSet.getString("username"),
									resultSet.getString("password"), resultSet.getString("email"),
									resultSet.getBoolean("is_admim"));
						}
					});
		}
		catch (IncorrectResultSizeDataAccessException e)
		{
			Logger logger = Logger.getLogger(CustomerDAOImpl.class);
			logger.error(e.getMessage());
			return null;
		}
		catch (DataAccessException e)
		{
			Logger logger = Logger.getLogger(CustomerDAOImpl.class);
			logger.error(e.getMessage());
			return null;
		}
	}

}
